package com.itheima.Intercepter;

import com.aliyun.properties.JwtProperties;
import com.itheima.common.BaseContext;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class Intercepter implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                            Object handler){
       if(!(handler instanceof HandlerMethod)){
           return true;
       }
      String jwt= request.getHeader(jwtProperties.getTokenName());
       try{
           Map map= Jwts.parser()
                   .setSigningKey(jwtProperties.getSecretKey())
                   .parseClaimsJws(jwt).getBody();
           System.out.println(map);
           BaseContext.setThreadLocalid((Integer)map.get("id"));
       }catch (SignatureException e){
           System.out.println("签名验证失败");
           response.setStatus(401);
           return false;
       }catch (ExpiredJwtException e){
           System.out.println("token过期");
           response.setStatus(401);
           return false;
       }catch (IllegalArgumentException e){
           System.out.println("非法参数");
           response.setStatus(401);
           return false;
       }
       return true;

   }
}
